package com.bawei.lib_common

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.SystemClock
import android.util.TypedValue
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.lib_common.base.BaseApplication

import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch



/**
 * @author lixinyu
 * @description 封装所有扩展函数
 * @date 2025/5/12
 */


fun <T> Flow<T>.observeWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    minState:Lifecycle.State = Lifecycle.State.RESUMED,
    action:suspend (T) -> Unit
):Job = lifecycleOwner.lifecycleScope.launch {
    lifecycleOwner.repeatOnLifecycle(minState){
        collectLatest {
            action.invoke(it)
        }
    }
}

//获取属性值
fun getAttrValue(context: Context, attrId: Int): Int {
    val typedValue = TypedValue()
    context.theme.resolveAttribute(attrId, typedValue, true)
    return typedValue.resourceId
}

val appContext: Context
    get() = BaseApplication.instance

//dp转px 按照dp单位绘制，根据手机dpi屏幕像素密码绘制对应px
//val Int.dp: Int
//    get() = AutoSizeUtils.dp2px(appContext, this.toFloat())
//
//val Float.dp: Float
//    get() = AutoSizeUtils.dp2px(appContext, this).toFloat()
//val Float.sp: Float
//    get() = AutoSizeUtils.sp2px(appContext, this).toFloat()
//按键消抖
fun View.clickFlow() = callbackFlow {
    setOnClickListener {
        trySend(Unit).onFailure { e -> e?.printStackTrace() }
    }
    awaitClose { setOnClickListener(null) }
}

fun <T> Flow<T>.throttleFirst(thresholdMillis: Long) = flow {
    var lastTime = 0L
    collect { upstream ->
        val currentTime = SystemClock.elapsedRealtime()
        if (currentTime - lastTime >= thresholdMillis) {
            lastTime = currentTime
            emit(upstream)
        }
    }
}

fun Int.formatCount(): String {
    if (this >= 10000) {
        val w = this / 10000
        return "${w}w+"
    }
    return this.toString()
}

fun Long.formatCount(): String {
    if (this >= 10000) {
        val w = this / 10000
        return "${w}w+"
    }
    return this.toString()
}


//图标变色
fun tint(drawable: Drawable, color: Int): Drawable {
    val new = DrawableCompat.wrap(drawable).mutate()
    DrawableCompat.setTint(new, ContextCompat.getColor(appContext, color))
    return new
}

fun tintDrawable(drawable: Drawable?, colors: Int): Drawable {
    val wrappedDrawable = DrawableCompat.wrap(drawable!!).mutate()
    DrawableCompat.setTint(wrappedDrawable, colors)
    return wrappedDrawable
}